package com.hula.onion.book.server.dao.impl;

import com.hula.onion.book.server.dao.IDiscoverDao;
import com.hula.onion.book.server.model.News;
import com.hula.onion.book.server.model.NewsDetail;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Collections;
import java.util.List;

/**
 * Created by work on 2018/2/25.
 */
@Repository
public class DiscoverDaoImpl extends JdbcDaoSupport implements IDiscoverDao {

    @Resource(name = "dataSource")
    private DataSource dataSource;

    DiscoverDaoImpl(DataSource dataSource) {
        setDataSource(dataSource);
    }

    private static final BeanPropertyRowMapper<News> mapper =
            new BeanPropertyRowMapper<>(News.class);

    private static final BeanPropertyRowMapper<NewsDetail> detailMapper =
            new BeanPropertyRowMapper<>(NewsDetail.class);

    private static final String GET_NEWS_LIST = "select * from news order by date desc limit ?,?;";

    @Override
    public List<News> getNewsList(int page, int size) {
        int from = page * size;
        List<News> result = this.getJdbcTemplate().query(GET_NEWS_LIST,
                new Object[]{from, size}, mapper);
        if (CollectionUtils.isEmpty(result)) {
            return Collections.emptyList();
        }
        return result;
    }

    private static final String GET_NEWS_DETAIL = "select * from news where id=?;";

    @Override
    public NewsDetail getNewsDetail(int newsId) {
        List<NewsDetail> result = this.getJdbcTemplate().query(GET_NEWS_DETAIL,
                new Object[]{newsId}, detailMapper);
        if (CollectionUtils.isEmpty(result)) {
            return null;
        }
        return result.get(0);
    }
}
